package com.auto.learning.adapter;

import java.util.ArrayList;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.auto.learning.R;
import com.auto.learning.activity.PlayActivity;
import com.auto.learning.bean.BookBean;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.MusicPlayManager;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.CommonAlertDialog;
import com.auto.learning.view.SharedPreferencesUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class HomePageNewListAdapter extends BaseAdapter {
	
	private ArrayList<BookBean> list;
	private Context context;
	private int type = 1;  //1，最新   2，周榜
	DisplayImageOptions options;
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			
		};
	};
	
	public HomePageNewListAdapter(Context context,ArrayList<BookBean> list,int type){
		this.context = context;
		this.list = list;
		this.type = type;
		initImageLoader();
	}
	
	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return list.get(position).getBookId();
	}

	ViewHolder holder;
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final BookBean bean = list.get(position);
		if (convertView == null) {
			holder = new ViewHolder();
			if (type == 1) {
				convertView = LayoutInflater.from(context).inflate(R.layout.homepage_new_list_adapter, null);
			}else if (type == 2){
				convertView = LayoutInflater.from(context).inflate(R.layout.homepage_new_list_adapter_1, null);
			}
			holder.image_face = (ImageView) convertView.findViewById(R.id.image_face);
			holder.f_image_play = (ImageView) convertView.findViewById(R.id.f_image_play);
			holder.tv_bookname = (TextView) convertView.findViewById(R.id.tv_bookname);
			holder.tv_slogn = (TextView) convertView.findViewById(R.id.tv_slogn);
			holder.tv_pinglun_number = (TextView) convertView.findViewById(R.id.tv_pinglun_number);
			holder.tv_shoucang_number = (TextView) convertView.findViewById(R.id.tv_shoucang_number);
			holder.tv_listen_number = (TextView) convertView.findViewById(R.id.tv_listen_number);
			holder.rel_listen = (RelativeLayout) convertView.findViewById(R.id.rel_listen);
			holder.linear_bottom = (LinearLayout) convertView.findViewById(R.id.linear_bottom);
			holder.image_is_read = (ImageView) convertView.findViewById(R.id.image_is_read);
			convertView.setTag(holder);
		}else {
			holder = (ViewHolder) convertView.getTag();
		}
		ImageLoader.getInstance().displayImage(bean.getFaceImgPlay(), holder.image_face,options);
		holder.tv_bookname.setText(bean.getBookName() + "");
		holder.tv_listen_number.setText(bean.getListenNum()+"");
		holder.tv_pinglun_number.setText(bean.getCommentNum()+"");
		holder.tv_shoucang_number.setText(bean.getFavorNum()+"");
		holder.tv_slogn.setText(bean.getSlogan()+"");
		if (bean.getIsRead() == 2) {
			holder.image_is_read.setVisibility(View.VISIBLE);
			holder.image_is_read.setImageResource(R.drawable.yidu);
		}else {
			holder.image_is_read.setVisibility(View.GONE);
		}
		int playingBookId[] = MusicPlayManager.getInstance(context).isPlayingBookId();
		if (playingBookId[0] != 0 && playingBookId[0] == bean.getBookId()) {
			if (playingBookId[2] == 0) 
				holder.f_image_play.setImageResource(R.drawable.playing);
			else 
				holder.f_image_play.setImageResource(R.drawable.play);
		}else {
			holder.f_image_play.setImageResource(R.drawable.play);
		}
		if (type == 1) {
			holder.rel_listen.setVisibility(View.GONE);
			holder.linear_bottom.setVisibility(View.GONE);
			holder.tv_slogn.setVisibility(View.VISIBLE);
		}else if (type == 2) {
			holder.rel_listen.setVisibility(View.GONE);
			holder.linear_bottom.setVisibility(View.VISIBLE);
			holder.tv_slogn.setVisibility(View.GONE);
		}
		holder.f_image_play.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				final MusicPlayManager manager = MusicPlayManager.getInstance(context);
				int ids[] = manager.isPlayingBookId();
				if (ids[0] == 0 || ids[0] != bean.getBookId()) {
					playDialog(bean);
				}else {
					manager.pause();
				}
			}
		});
		return convertView;
	}
	
	public void showDialog(final BookBean bookBean){
		CommonAlertDialog alertDialog = new CommonAlertDialog(context);
		alertDialog.setTextMessage(String.format(context.getResources().getString(R.string.play_size_notice), CommonMethod.calculationNum(bookBean.getProSize()+bookBean.getEnSize() + bookBean.getDoubiSize())));
		alertDialog.setShowTitle(true);
		String[] a = {context.getResources().getString(R.string.app_continue),context.getResources().getString(R.string.app_cancel)};
		alertDialog.setBtns(new DialogListener() {
			
			@Override
			public void okButtonClick(Dialog dialog) {
				play(bookBean);
				MusicPlayManager.getInstance(context).setShowNetTips(false);
				dialog.dismiss();
			}

			@Override
			public void cancelButtonClick(Dialog dialog) {
				CommonMethod.reordPlayStatus(context, bookBean.getBookId(), true);
				dialog.dismiss();
			}

			@Override
			public void otherButtonClick(Dialog dialog) {
				CommonMethod.reordPlayStatus(context, bookBean.getBookId(), true);
				dialog.dismiss();
			}
		},a);
		alertDialog.show();
	}
	
	
	public void playDialog(final BookBean bookBean){
		if (TemporaryVariable.downLoadedList.contains(bookBean.getBookId())) {
			play(bookBean);
		}else {
			if ((boolean)SharedPreferencesUtils.getParam(context, HttpRequestHelper.DWONLOAD_PLAY_CONTINUE, false)) {
				play(bookBean);
			} else {
				switch (CommonMethod.getNetworkState(context)) {
				case 0:
					CommonMethod.makeNotice(context, context.getResources().getString(R.string.connect_err_io));
					break;
				case 1:
					play(bookBean);
					break;
				case 2:
					showDialog(bookBean);
					break;
				}
			}
		}
	}
	
	private void play(final BookBean bookBean){
		handler.postDelayed(new Runnable() {
			public void run() {
				ArrayList<BookBean> m_list = new ArrayList<BookBean>();
				if (CommonMethod.getNetworkState(context) == 1) {
					m_list.addAll(list);
				}else {
					m_list.add(bookBean);
					int index = list.indexOf(bookBean);
					for (int k = index - 1; k >= 0; k-- ) {
						if (TemporaryVariable.downLoadedList.contains(list.get(k).getBookId())) {
							m_list.add(0,list.get(k));
						} else {
							break;
						}
					}
					for (int i = index + 1; i < list.size(); i++) {
						if (TemporaryVariable.downLoadedList.contains(list.get(i).getBookId())) {
							m_list.add(list.get(i));
						} else {
							break;
						}
					}
				}
				MusicPlayManager.getInstance(context).setPlayList(m_list).setBookId(bookBean.getBookId()).play();
			}
		}, 1500);
		TemporaryVariable.read_list.clear();
		for (int i = 0; i < list.size(); i++) {
			TemporaryVariable.read_list.add(list.get(i).getBookId());
		}
		Intent intent = new Intent(context, PlayActivity.class);
		intent.putExtra("bookId", bookBean.getBookId());

		intent.putExtra("canRead",bookBean.getCanRead());
		intent.putExtra("needBuy", bookBean.getNeedBuy());
		intent.putExtra("faceImg", bookBean.getFaceImg());
		context.startActivity(intent);
	}
	
	class ViewHolder{
		ImageView image_face,f_image_play,image_is_read;
		TextView tv_bookname,tv_slogn,tv_pinglun_number,tv_shoucang_number,tv_listen_number;
		RelativeLayout rel_listen;
		LinearLayout linear_bottom;
	}
	
	private void initImageLoader(){
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.default_512)
		.showImageForEmptyUri(R.drawable.default_512)
		.showImageOnFail(R.drawable.default_512).cacheInMemory(true)
		.cacheOnDisk(true).considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565).build();
	}
}
